package com.demo.module.scheduler;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
public class AutoDataBaseInitScheduler {

    public List<String> MONTHS = Arrays.asList("01","02","03","04","05","06","07","08","09","10","11","12");

    @Value("${my.sharding.create-table.url}")
    private String datasourceUrl;


    @Value("${my.sharding.create-table.username}")
    private String datasourceUsername;


    @Value("${my.sharding.create-table.password}")
    private String datasourcePassword;

    /**
     * 执行SQL
     * @param sqlList SQL集合
     */
    private  void executeSql(List<String> sqlList) {
        List<String> tableNames = createTableNames();
        if (StringUtils.isEmpty(datasourceUrl) || StringUtils.isEmpty(datasourceUsername) || StringUtils.isEmpty(datasourcePassword)) {
            log.error("数据库连接配置有误，请稍后重试，URL:{}, username:{}, password:{}", datasourceUrl, datasourceUsername, datasourcePassword);
            throw new IllegalArgumentException("数据库连接配置有误，请稍后重试");
        }
        //创建表
        tableNames.forEach(e->createMysqlTbale(e,sqlList));
    }

    private void createMysqlTbale(String tableNames, List<String> sqlList) {
//        Collections.singletonList("CREATE TABLE IF NOT EXISTS `" + resultTableName + "` LIKE `" + logicTableName + "`;")
        try (Connection conn = DriverManager.getConnection(datasourceUrl.replace("sharding_test", tableNames), datasourceUsername, datasourcePassword)) {
            try (Statement st = conn.createStatement()) {
                conn.setAutoCommit(false);
                for (String sql : sqlList) {
                    st.execute(sql);
                }
            } catch (Exception e) {
                conn.rollback();
                log.error("数据表创建执行失败，请稍后重试，原因：{}", e.getMessage(), e);
                throw new IllegalArgumentException("数据表创建执行失败，请稍后重试");
            }
        } catch (SQLException e) {
            log.error("数据库连接失败，请稍后重试，原因：{}", e.getMessage(), e);
            throw new IllegalArgumentException("数据库连接失败，请稍后重试");
        }

    }

    private List<String> createTableNames() {
        List<String> result = new ArrayList<>();
        //当年所有月份
        LocalDate now = LocalDate.now();
        Integer year = now.getYear();
        List<String> yearMonth = MONTHS.stream().map(e -> (year + e))
                .collect(Collectors.toList());
        result.addAll(yearMonth);
        //预创建第二年数据
        if (now.getMonth().getValue() > 6) {
            List<String> nextYearMonth = MONTHS.stream().map(e -> ((year+1) + e))
                    .collect(Collectors.toList());
            result.addAll(nextYearMonth);
        }
        return result;
    }
}
